from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
import metroscope.settings as settings
import metroscope.codewiki.models as models
from metroscope.codewiki.postdata import MatchEvent, MakeEvent, AddUser, ResetDatabase, SaveReading
from django.contrib.auth.models import User
import os
import re
import datetime


class ScopeForm(forms.Form):
    user_name   = forms.CharField(required=True)
    user_password= forms.CharField(required=True)
    user_email  = forms.EmailField(required=False, widget=forms.TextInput(), help_text="when adding new user")
    title       = forms.CharField(required=False, widget=forms.TextInput(), help_text="title of the event")
    summary     = forms.CharField(required=False, widget=forms.TextInput(), help_text="extra text description")
    url         = forms.URLField(required=False, widget=forms.TextInput(), help_text="link for the event")
    source      = forms.CharField(required=False, widget=forms.TextInput(), help_text="source or type of event")
    refid       = forms.CharField(required=False, widget=forms.TextInput(), help_text="reference id used in the source database") 
    evt_time	= forms.DateTimeField(required=False, widget=forms.TextInput(), help_text="time of the event")
    postcode    = forms.CharField(required=False, widget=forms.TextInput())
    lat         = forms.FloatField(required=False, widget=forms.TextInput(), help_text="GPS latitude (float)")
    lon         = forms.FloatField(required=False, widget=forms.TextInput(), help_text="GPS longitude (float)")
    radius      = forms.FloatField(required=False, widget=forms.TextInput(), help_text="Metres radius of event")
    district    = forms.CharField(required=False, widget=forms.TextInput(), help_text="to clear records enter 'delete all src'")
    related_evt = forms.IntegerField(required=False, widget=forms.TextInput(), help_text="messid of a related event (eg to event begins)")
    quantity	= forms.FloatField(required=False, widget=forms.TextInput(), help_text="float value (eg monetary amount)")

    non_replace_field = forms.CharField(required=False, widget=forms.TextInput(), help_text="don't save record matching this field exists")


def scopeusers(request):
    scopeusers = models.ScopeUser.objects.all()
    return render_to_response('scopeusers.html', {'scopeusers':scopeusers, 'settings':settings})

def scopeuser(request, username):
    scopeusers = models.ScopeUser.objects.filter(name=username)
    if not scopeusers:
        return render_to_response('scopeout.html', {'message':"No matching user", 'settings': settings})
    scopeuser = scopeusers[0]
    
    sourcesmap = { }
    for scopeevent in scopeuser.scopeevent_set.all():
        sourcesmap.setdefault(scopeevent.source, 0)
        sourcesmap[scopeevent.source] += 1
    
    sourcesnum = sorted(list(sourcesmap.iteritems()))
    scopeevents = scopeuser.scopeevent_set.all()
    return render_to_response('scopeuser.html', {'scopeuser':scopeuser, 'sourcesnum':sourcesnum, 'scopeevents':scopeevents, 'settings':settings})

def scopeusersourcename(request, username, sourcename):
    scopeusers = models.ScopeUser.objects.filter(name=username)
    if not scopeusers:
        return render_to_response('scopeout.html', {'message':"No matching user", 'settings': settings})
    scopeuser = scopeusers[0]
    scopeevents = scopeuser.scopeevent_set.filter(source=sourcename)
    
    return render_to_response('scopeuser.html', {'scopeuser':scopeuser, 'scopeevents':scopeevents, 'settings':settings})
    
    
# unable to make the string 'detectors' be included into the urls function
def scopeindex(request):
    actionmessage = ""
    if request.POST.get("reset"):
        ResetDatabase()
        actionmessage = "The database has been reset"
    if request.POST.get("savereadings"):
        for reading in models.ScrapedText.objects.all():
            SaveReading(reading)
        actionmessage = "The readings have been saved"
        
    return render_to_response('scopeindex.html', {'detectors':'detectors', 'readers':'readers', 'collectors':'collectors', 'observers':'observers', 'settings':settings, 'actionmessage':actionmessage})


def scopesubmit(request):
    message = "none"
    rform = ScopeForm(request.GET)  
    if not rform.is_valid():
        message = request.method + "  " + str(rform.errors)
        return render_to_response('scopesubmit.html', {'form':ScopeForm(), 'message':message, 'settings': settings})

    # get the location
    # or manage its setting from the parser?

    # add new user if possible
    if rform.data.get("user_email"):
        message = AddUser(rform.data)
        return render_to_response('scopeout.html', {'message':message, 'settings': settings})

    mevts = MatchEvent(rform.data)
    if mevts:
        message = "Matching events already there: " + str(mevts)
        models.ScopeEvent.delete(mevts[0])
        MakeEvent(rform.data)  # over-write
    else:
        message = MakeEvent(rform.data)
    return render_to_response('scopeout.html', {'message':message, 'settings': settings})

def scopescroll(request):
    message = "none"
    return render_to_response('scopescroll.html', {'message':message, 'settings': settings})
    

def scopeabout(request):
    message = "none"
    return render_to_response('scopeabout.html', {'message':message, 'settings': settings})

